<?php
/**
 * Created by PhpStorm.
 * User: jswei
 * Date: 2018/5/3
 * Time: 14:06
 */
namespace app\first\model;

use think\Db;
use think\Model;

class HomeComView extends Model{
    protected $autoWriteTimestamp = true;
    /**
     * @param array $where
     * @param string $order
     * @param int $limit
     * @param string $filedÍ
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getList($where=[],$order='create_time desc',$limit=10,$filed='*'){
        $list = $this
            ->field('id,create_time')
            ->with(['article','article'])
            ->where($where)
            ->order($order)
            ->paginate($limit);
        return $list;
    }

    public function article(){
        return $this->hasOne('user','id','aid')
            ->bind([
                'title',
                'address',
                'city_id',
                'location',
            ]);
    }

    public function user(){
        return $this->hasOne('Member','id','mid')
            ->bind([
                'account',
                'avatar',
                'address',
                'nickname'
            ]);
    }

    /**
     * @param $aid
     * @param $uid
     * @param string $out
     * @return bool
     */
    public function addNew($aid,$uid,&$out=''){
        $com = new HomeCom();
        $info = $com->find($aid);
        if(!$info){
            $out = '推荐不存在';
            return false;
        }
        $data = [
            'aid'=>$aid,
            'mid'=>$uid
        ];
        $valid = new \app\first\validate\HomeComView();
        if(!$valid->check($data)){
            $out = $valid->getError();
            return false;
        }
        Db::startTrans();
        $result = $this->save($data);
        $info->hits = $info['hits']+1;
        $result1 = $info->save();
        if($result && $result1){
            Db::commit();
            return true;
        }else{
            Db::rollback();
            $out = '操作失败';
            return false;
        }
    }
}